import os
import sys
import datetime
import requests
import ctypes
import win32api
import win32con
from PIL import Image, ImageDraw

# --- 路径与系统功能 ---
Image.MAX_IMAGE_PIXELS = None


def resource_path(relative_path):
    """ 获取资源的绝对路径，兼容开发环境和PyInstaller打包环境 """
    if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
        base_path = sys._MEIPASS
    else:
        base_path = os.path.abspath(".")
    return os.path.join(base_path, relative_path)


def manage_startup(enable):
    """ 管理程序的开机自启状态 """
    if sys.platform != 'win32':
        return
    try:
        app_path = sys.executable
        app_name = os.path.splitext(os.path.basename(app_path))[0]
        startup_folder = os.path.join(os.getenv('APPDATA'), 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup')
        shortcut_path = os.path.join(startup_folder, f"{app_name}.lnk")
        if enable:
            from win32com.client import Dispatch
            shell = Dispatch('WScript.Shell')
            shortcut = shell.CreateShortCut(shortcut_path)
            shortcut.TargetPath = app_path
            shortcut.WorkingDirectory = os.path.dirname(app_path)
            shortcut.save()
        elif os.path.exists(shortcut_path):
            os.remove(shortcut_path)
    except Exception as e:
        print(f"开机自启设置失败: {e}")


def get_screen_resolution():
    """ 获取真实的屏幕物理分辨率 """
    if sys.platform == 'win32':
        return win32api.GetSystemMetrics(win32con.SM_CXSCREEN), win32api.GetSystemMetrics(win32con.SM_CYSCREEN)
    return 1920, 1080


def set_wallpaper(image_path):
    """ 设置桌面壁纸 """
    abs_path = os.path.abspath(image_path)
    if sys.platform != 'win32':
        return False
    try:
        return bool(ctypes.windll.user32.SystemParametersInfoW(20, 0, abs_path, 3))
    except Exception as e:
        print(f"设置壁纸时发生错误: {e}")
        return False


# --- URL 与图片处理 ---

def create_satellite_url_generator(url_template, delay_minutes, interval_minutes=15):
    """ 卫星URL生成器工厂 """

    def generate_url():
        now_utc = datetime.datetime.now(datetime.timezone.utc)
        target_time = now_utc - datetime.timedelta(minutes=delay_minutes)
        start_minute = (target_time.minute // interval_minutes) * interval_minutes
        start_time = target_time.replace(minute=start_minute, second=0, microsecond=0)
        end_time = start_time + datetime.timedelta(minutes=interval_minutes - 1, seconds=59)
        start_str = start_time.strftime("%Y%m%d%H%M%S")
        end_str = end_time.strftime("%Y%m%d%H%M%S")
        return url_template.format(start_time=start_str, end_time=end_str)

    return generate_url


def download_image(url, save_path):
    """ 下载图片 """
    try:
        headers = {'User-Agent': 'Mozilla/5.0'}
        response = requests.get(url, stream=True, timeout=60, headers=headers)
        if response.status_code == 200:
            os.makedirs(os.path.dirname(save_path), exist_ok=True)
            with open(save_path, 'wb') as f:
                for chunk in response.iter_content(8192):
                    f.write(chunk)
            return True
    except requests.exceptions.RequestException as e:
        print(f"下载错误: {e}")
    return False


def process_image(input_path, output_path, target_width, target_height, source_name=None, need_resize=True):
    """ 通过“填充并裁剪”处理图片 """
    try:
        with Image.open(input_path) as img:
            img_width, img_height = img.size
            if source_name == '世界区域':
                img = img.crop((0, 80, img_width, img_height - 96))
            elif source_name == '中国区域':
                img = img.crop((0, 519, img_width, img_height - 292))
            else:
                img = img.crop((0, 20, img_width, img_height - 950))
                draw = ImageDraw.Draw(img)
                draw.rectangle((0, 0, 1750, 525), (0, 0, 0))

            if need_resize:
                img_width, img_height = img.size
                img_ratio = img_width / img_height
                target_ratio = target_width / target_height
                if img_ratio > target_ratio:
                    new_h = target_height
                    new_w = int(new_h * img_ratio)
                    resized = img.resize((new_w, new_h), Image.Resampling.LANCZOS)
                    left = (new_w - target_width) / 2
                    final = resized.crop((left, 0, left + target_width, new_h))
                else:
                    new_w = target_width
                    new_h = int(new_w / img_ratio)
                    resized = img.resize((new_w, new_h), Image.Resampling.LANCZOS)
                    final = resized.crop((0, 0, new_w, target_height))
                final.save(output_path, 'JPEG', quality=95)
            else:
                img.save(output_path, 'JPEG', quality=95)
            return True
    except Exception as e:
        print(f"处理图片时发生错误: {e}")
    return False
